import React from 'react'
// ===================================================================== Temp
import SearchForm from '#cpt/temp/SearchForm'
import Table from '#cpt/temp/Table'
import TableControls from '#cpt/temp/TableControls'
import Controls from '#cpt/temp/Controls'
import { MultipleType,CheckType } from '@views/novel-coro-system/test-info/common/defaultData'
// ===================================================================== global declare
const { $fn, $Lazy, globalConfig, $http } = window
const { COVIDUrl } = globalConfig
// ===================================================================== Lazy
const $cache 				= $Lazy.file(()=>import('#private/cache-api'))
const $time 				= $Lazy.file(()=>import('@com/utils/time'))
const ModifyTimeModal 		= $Lazy.state(()=>import('./modify-time-modal'))
const AbnormalReportModal 	= $Lazy.state(()=>import('./abnormal-report-modal'))
const BatchAuditModal 		= $Lazy.state(()=>import('./batch-audit-modal'))
const PatientInfoModal		= $Lazy.state(()=>import('../../common/patient-info-modal'))
const confirm 				= $Lazy.file(()=>import('@antd/confirm'))
// ===================================================================== component
class Index extends React.Component{
	state = {
		data:[],
		pag: {},
		selectedKeys:[],
		selectedRows:[],
		// 搜索表单列表
		forms : [
			{ label: '创建时间',			names: ['create_at_start','create_at_end'], type:'date-range', name:'jz-time' },
			{ label: '报告单编号',		name: 'report_num' },
			{ label: '标本条码',			name: 'spec_code' },
			{ label: '医院',				name: 'hosp_id',	type: 'select', loading:true,	idStr:'uuid',	nameStr:'hospName' },
			{ label: '姓名',				name: 'patient_name' },
			{ label: '证件号',			name: 'card_no' },
			{ label: '采集类型',			name: 'isMultiple',			type:'select',		data:MultipleType },
			{ label: '受检类型',			name: 'checkType',			type:'select',		data:CheckType },
			{ label: '接收时间',			names: ['check_time_start','check_time_end'], type:'date-range', name:'jz-time1' },
		],
	}
	
	model = {}
	permissions = {updatereportat:1,reportstate:1 }
	componentDidMount(){
		const { ban_btn } = $fn.local('permissions')
		if($fn.hasArray(ban_btn)){
			if(ban_btn.includes('caseinfo.updatereportat')){		// 修改报告时间
				this.permissions.updatereportat = 0
			}
			if(ban_btn.includes('caseinfo.reportstate')){		// 召回、异常
				this.permissions.reportstate = 0
			}
		}
		this.getSelect()
	}
	onTime = reset => {
		 $time.then(f=>{
			const arr = f.duration['2-9-now']()
			this.resetModel = { create_at_start: arr[0], create_at_end: arr[1], 'jz-time':arr }
			this.model = $fn.copy(this.resetModel)
			this.fetch()
		})
	}
	
	// 获取下拉数据
	getSelect = () => {
		const { forms } = this.state
		
		$cache.then( async f => {
			// 医院
			this.hostData = await f.getCache({ api:COVIDUrl+'Hospital/query',param:{page:1,page_num:10000,status:1} } )
			$fn.setRow(forms, 'hosp_id', this.hostData )
			this.setState({ forms })
			this.onTime()
		})
	}
	
	// paging
	fetch = () => $fn.fetch.call(this,COVIDUrl+'caseinfo/query',{param:{report_state:1,status:1},COVID:true})
	
	// 表单
	cols = [
		{ title: '报告单编号',		dataIndex: 'reportNum', 		...$fn.table.spec_num },
		{ title: '标本条码', 		dataIndex: 'specCode', 			...$fn.table.spec_code },
		{ title: '姓名', 			dataIndex: 'patientName', 		...$fn.table.name  },
		{ title: '所属医院', 		dataIndex: 'hospId', 			width:200,				render: text => $fn.getState(this.hostData,text,'hospName','uuid') },
		{ title: '证件号', 			dataIndex: 'cardNo', 			...$fn.table.idcard },
		{ title: '送检科室', 		dataIndex: 'departmentName', 	width:180 },
		{ title: '受检类型', 		dataIndex: 'checkType', 		width:100,	render: text => $fn.getState(CheckType,text) },
		{ title: '采集类型', 		dataIndex: 'isMultiple', 		width:100,	render: text => $fn.getState(MultipleType,text) },
		{ title: '创建时间', 		dataIndex: 'createdAt', 		...$fn.table.time },
		{ title: '采样时间', 		dataIndex: 'collTime', 			...$fn.table.time },
		{ title: '接收时间', 		dataIndex: 'checkTime', 			...$fn.table.time },
		TableControls.controls.call(this, { width: 150})
	]
	// 表格操作按钮
	table_controls = (text,{ uuid, reportNum, collTime, checkTime, specCode }) => {
		const {reportstate } = this.permissions
		return [
			TableControls.pushTo.call(this,'预览', `preview-report?report_num=${reportNum}`),
			reportstate && TableControls.click.call(this,'审核', () => {
				const nowDate = new Date().valueOf()
				const coll = new Date(collTime).valueOf() //采样时间
				const check = new Date(checkTime).valueOf() //接收时间
				const timeout1 = nowDate - coll > (24*3600000) //超时
				const timeout2 = coll > check //采样时间大于接收时间
				let msg = '确认审核?'
				if (timeout1 && timeout2) {
					msg = `条码【${specCode}】已超过24小时并且接收时间大于采样时间，是否确认审核?`
				} else if (timeout1) {
					msg = `条码【${specCode}】已超过24小时，是否确认审核?`
				} else if (timeout2) {
					msg = `条码【${specCode}】采样时间大于接收时间，是否确认审核?`
				}
				confirm.then( f => {
					f({
						msg,
						onOk: async close => {
							$http.submit(null, COVIDUrl+'caseinfo/reportState',{ param:{status:2,uuids:uuid}, loadingText:`审核中`}).then(()=>{
								close()
								this.fetch()
								$fn.msg.success('审核成功')
							})
						}
					})
				})
			}),
			TableControls.click.call(this,'编辑',()=>this.patientInfoModal.open(uuid))
		]
	}
	// 操作按钮
	controls = () => {
		const { selectedKeys, selectedRows } = this.state
		const uuids = selectedKeys.join(',')
		const reportNum = selectedRows.map(v=>v.reportNum).join(',')
		let specArr = selectedRows.map(v=>v.specCode)		// 选中条码
		let specCodes = []		//	选中超过24小时条码
		let specCodes2 = []		//	选中条码采样时间大于接收时间
		if($fn.hasArray(selectedRows)){
			const nowDate = new Date().valueOf()
			selectedRows.forEach(v=>{
				const coll = new Date(v.collTime).valueOf()
				const check = new Date(v.checkTime).valueOf()
				if(nowDate - coll > (24*3600000)){
					specCodes.push(v.specCode)
				}
				if(coll > check){
					specCodes2.push(v.specCode)
				}
			})
		}
		specCodes = Array.from(new Set(specCodes))
		specCodes2 = Array.from(new Set(specCodes2))
		specArr = Array.from(new Set(specArr))
		const {updatereportat,reportstate } = this.permissions
		return [
			Controls.pushTo.call(this,'预览', `preview-report?report_num=${reportNum}`, {isKeys:true}),
			reportstate && Controls.click.call(this,'批量审核',()=>{
				if ($fn.hasArray(specCodes) || $fn.hasArray(specCodes2)) {
					this.bAudittRef.open(uuids,specCodes, specCodes2)
				} else {
					confirm.then( f => {
						f({
							msg: '确认审核?',
							onOk: async close => {
								$http.submit(null, COVIDUrl+'caseinfo/reportState',{ param:{status:2, uuids}, loadingText:`审核中`}).then(()=>{
									close()
									this.fetch()
									$fn.msg.success('审核成功')
								})
							}
						})
					})
				}
			},{isKeys:1}),
			updatereportat && Controls.click.call(this,'修改报告时间',()=>this.modifyTimeRef.open(uuids),{isKeys:1}),
			reportstate && Controls.click.call(this,'异常报告',()=>this.aReportRef.open(uuids,specArr),{isKeys:1}),
		]
	}
	render(){
		return (
			<>
				{/* 搜索 */}
				{ SearchForm.call(this,{ timeStr:'2-9-now' }) }
				{/* 表格 */}
				{ Table.call(this) }
				{/* 审核 */}
				<BatchAuditModal onRef={ref=>this.bAudittRef=ref} onRefresh = {()=>{
					this.setState({selectedKeys:[],selectedRows:[]})
					this.fetch()
				}} />
				{/* 修改报告时间 */}
				<ModifyTimeModal onRef={ref=>this.modifyTimeRef=ref} onRefresh = {this.fetch} />
				{/* 异常报告 */}
				<AbnormalReportModal onRef={ref=>this.aReportRef=ref} onRefresh = {()=>{
					this.setState({selectedKeys:[],selectedRows:[]})
					this.fetch()
				}} />
				{/* 编辑 */}
				<PatientInfoModal onRef={ref => this.patientInfoModal = ref} onRefresh={ () => this.fetch() } />
			</>
		)
	}
}

export default Index